package com.ferris.redbook.service.impl;

import com.ferris.redbook.dto.request.LoginRequest;
import com.ferris.redbook.dto.request.RegisterRequest;
import com.ferris.redbook.dto.response.RegisterResponse;
import com.ferris.redbook.entity.User;
import com.ferris.redbook.mapper.UserMapper;
import com.ferris.redbook.service.AuthService;
import com.ferris.redbook.util.AjaxResult;
import com.ferris.redbook.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public AjaxResult login(LoginRequest request) {
//         1. 参数验证
        if (!StringUtils.hasText(request.getEmail()) || !StringUtils.hasText(request.getPassword())) {
            return AjaxResult.error(400, "邮箱或密码不能为空");
        }


        // 2. 查询用户
        User user = userMapper.selectByEmail(request.getEmail());
        if (user == null) {
            return AjaxResult.error(401, "用户不存在");
        }

        // 3. 验证密码
        if (!request.getPassword().equals(user.getPassword())) {
            return AjaxResult.error(401, "密码错误");
        }

        // 4. 检查用户状态
        if (user.getStatus() != 1) {
            return AjaxResult.error(403, "账户已被禁用");
        }

        // 5. 生成JWT令牌
        String token = jwtUtil.generateToken(user.getId(), user.getNickname());

        // 6. 更新最后登录时间
        user.setLastLogin(LocalDateTime.now());
        userMapper.updateById(user);

        // 7. 构建返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("email", user.getEmail());
        userInfo.put("nickname", user.getNickname());
        userInfo.put("avatar", user.getAvatar());
        userInfo.put("bio", user.getBio());
        userInfo.put("gender", user.getGender());
        userInfo.put("location", user.getLocation());
        userInfo.put("birthday", user.getBirthday());
        userInfo.put("createdAt", user.getCreatedAt());

        data.put("user", userInfo);

        return AjaxResult.success("登录成功", data);
    }

    @Override
    @Transactional
    public AjaxResult register(RegisterRequest request) {
        // 1. 检查邮箱是否已存在
        Integer emailCount = userMapper.countByEmail(request.getEmail());
        if (emailCount != null && emailCount > 0) {
            return AjaxResult.error(400, "邮箱已被注册");
        }

        // 2. 检查昵称是否已存在
        Integer nicknameCount = userMapper.countByNickname(request.getNickname());
        if (nicknameCount != null && nicknameCount > 0) {
            return AjaxResult.error(400, "昵称已被使用");
        }

        // 3. 创建用户实体
        User user = User.builder()
                .email(request.getEmail())
                .password(request.getPassword())
                .nickname(request.getNickname())
                .avatar("avatars/001.jpg")
                .status(1)
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .build();

        // 4. 插入用户数据
        int result = userMapper.insert(user);
        if (result <= 0) {
            return AjaxResult.error("注册失败，请稍后重试");
        }

        // 5. 构建响应数据
        RegisterResponse response = RegisterResponse.builder()
                .id(user.getId())
                .email(user.getEmail())
                .nickname(user.getNickname())
                .createdAt(user.getCreatedAt())
                .build();

        return AjaxResult.success("注册成功", response);
    }
}